﻿using System;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Media;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using PomodoroSuite.EntidadesNegocio;
using PomodoroSuite.FrontEnd.Win.Properties;
using PomodoroSuite.FW.DAL;

namespace PomodoroSuite.FrontEnd.Win
{
    public partial class frmControlPomodoro : Form
    {
        #region " API "

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HTCAPTION = 0x2;
        [DllImport("User32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        #endregion

        #region " Campos "

        private Tarea tarea = null;
        private TareaSet tareaSet = null;
        private Pomodoro pomodoro = null;
        private int interrInternas = 0;
        private int interrExternas = 0;
        private static int nroPomodoros = 0;

        #endregion

        #region " Constructor "

        public frmControlPomodoro(Tarea tarea, TareaSet tareaSet)
        {
            InitializeComponent();
            this.tarea = tarea;
            if (tareaSet == null)
            {
                tareaSet = new TareaSet()
                {
                    IdTareaSet = 0,
                    EstadoTareaSet = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.Planeado,
                    HoraInicio = DateTime.Now,
                    NumeroPomodoros = 0,
                };
            }
            this.tareaSet = tareaSet;
            pomodoro = new Pomodoro()
            {
                IdPomodoro = 0,
                IdTareaSet = tareaSet.IdTareaSet,
                HoraInicio = DateTime.Now,
                EstadoPomodoro = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.Planeado,
                NumeroInterrupcionesExternas = 0,
                NumeroInterrupcionesInternas = 0,
            };
            this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Right - this.Width, Screen.PrimaryScreen.WorkingArea.Bottom - this.Height);
        }

        #endregion

        #region " Propiedades "

        public Tarea ObjTarea
        {
            get { return tarea; }
        }

        public TareaSet ObjTareaSet
        {
            get { return tareaSet; }
        }

        public Pomodoro ObjPomodoro
        {
            get { return pomodoro; }
        }

        #endregion

        #region " Eventos Formulario "

        private void frmControlPomodoro_Load(object sender, EventArgs e)
        {
            display.Minutes = ConfigurationManager.AppSettings["TiempoPomodoro"];
            lblTarea.Text = tarea.Nombre;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F2:
                    if (btnIniciar.Enabled)
                        btnIniciar_Click(null, EventArgs.Empty);
                    break;
                case Keys.F3:
                    if (btnCancelar.Enabled)
                        btnCancelar_Click(null, EventArgs.Empty);
                    break;
                case Keys.F4:
                    if (display.InProgress)
                        lblInterrInternas.Text = (++interrInternas).ToString();
                    break;
                case Keys.F5:
                    if (display.InProgress)
                        lblInterrExternas.Text = (++interrExternas).ToString();
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void frmControlPomodoro_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

        private void display_MouseMove(object sender, MouseEventArgs e)
        {
            frmControlPomodoro_MouseMove(sender, e);
        }

        private void frmControlPomodoro_Deactivate(object sender, EventArgs e)
        {
            this.Opacity = 0.5;
        }

        private void frmControlPomodoro_Activated(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }

        private void btnIniciar_Click(object sender, EventArgs e)
        {
            this.Text = display.Hours + ":" + display.Minutes + ":" + display.Seconds;
            display.Start();
            timer.Enabled = true;

            pomodoro.EstadoPomodoro = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.EnProgreso;
            pomodoro.HoraInicio = DateTime.Now;

            picClose.Visible = false;
            btnIniciar.Enabled = false;
            btnCancelar.Enabled = true;
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            display.Stop();
            timer.Enabled = false;

            pomodoro.HoraFinalizacion = DateTime.Now;
            pomodoro.EstadoPomodoro = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.Cancelado;

            btnCancelar.Enabled = false;
            picClose.Visible = true;

            GrabarInformacion();
        }

        private void picClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void display_Stopped(object sender, EventArgs e)
        {
            string rutaWav = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            SoundPlayer player = new SoundPlayer(rutaWav + "\\TimeUp.wav");
            player.Play();
            pomodoro.HoraFinalizacion = DateTime.Now;
            pomodoro.EstadoPomodoro = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.Terminado;
            tareaSet.NumeroPomodoros += 1;

            btnCancelar.Enabled = false;
            picClose.Visible = true;

            GrabarInformacion();
            nroPomodoros += 1;
            (Owner as Shell).IniciarDescanso(nroPomodoros);
            if (nroPomodoros == 4)
                nroPomodoros = 0;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            this.Text = display.CurrentTime;
            if (display.Finished)
                timer.Enabled = false;
        }

        #endregion

        #region " Métodos "

        private void GrabarInformacion()
        {
            try
            {
                if (tareaSet.IdTareaSet == 0)
                {
                    tareaSet.EstadoTareaSet = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.EnProgreso;
                    FabricaDAL.ObtenerDal<TareaSet>().Insertar(tareaSet);
                    tarea.EstadoTarea = PomodoroSuite.EntidadesNegocio.Enumeradores.Estado.EnProgreso;
                    tarea.IdTareaSet = tareaSet.IdTareaSet;
                    FabricaDAL.ObtenerDal<Tarea>().Actualizar(tarea);
                }
                else
                {
                    FabricaDAL.ObtenerDal<TareaSet>().Actualizar(tareaSet);
                }

                pomodoro.IdTareaSet = tareaSet.IdTareaSet;
                pomodoro.NumeroInterrupcionesExternas = interrExternas;
                pomodoro.NumeroInterrupcionesInternas = interrInternas;

                FabricaDAL.ObtenerDal<Pomodoro>().Insertar(pomodoro);
            }
            catch (Exception exc)
            {
                MessageBox.Show(Resources.comun_GrabarError + "\n" + exc.Message, Resources.comun_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion
    }
}
